package com.otod.cd.doc.service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.otod.base.service.BaseService;
import com.otod.cd.doc.bo.CdDocShareBo;
import com.otod.cd.doc.constants.ShareConstant;
import com.otod.cd.doc.mapper.CdDocFileUsageMapper;
import com.otod.cd.doc.mapper.CdDocFolderMapper;
import com.otod.cd.doc.mapper.CdDocShareAuthMapper;
import com.otod.cd.doc.mapper.CdDocShareMapper;
import com.otod.cd.doc.vo.CdDocFolderVo;
import com.otod.cd.doc.vo.CdDocShareAuthVo;
import com.otod.cd.doc.vo.CdDocShareVo;
import com.otod.commons.auth.SessionUserHolder;
import com.otod.commons.auth.SessionUserUtil;
import com.otod.commons.constants.CommonConstant;
import com.otod.commons.constants.LogConstant;
import com.otod.commons.utils.BeanUtils;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.StringUtils;
import com.otod.pm.prj.service.TeamService;
import com.otod.pm.prj.vo.TeamVo;
import com.otod.sys.emp.mapper.EmpMapper;
import com.otod.sys.emp.mapper.EmpOrgRoleMapper;
import com.otod.sys.emp.service.IEmpService;
import com.otod.sys.vo.AuapREmpOrgRoleVo;
import com.otod.sys.vo.AuapTEmpVo;

@Service
@Transactional(readOnly=true)
public class CdDocShareService extends BaseService {
	
		
	@Autowired
	CdDocFileUsageMapper cdDocFileUsageMapper;
	@Autowired
	CdDocFolderMapper docFileMapper;
	@Autowired
	CdDocShareMapper cdDocShareMapper;
	@Autowired
	CdDocShareAuthMapper cdDocShareAuthMapper;
	@Autowired
	CdDocShareAuthService cdDocShareAuthService;
	@Autowired
	IEmpService empService;
	@Autowired
	EmpOrgRoleMapper empOrgRoleMapper;
	@Autowired
	CdDocFileService cdDocFileService;
	@Autowired
	TeamService teamService;
	@Autowired
	EmpMapper empMapper;
	
	private static Logger logger = LoggerFactory.getLogger(CdDocShareService.class);


	/**
	 * 通过ID查询文件信息
	 * @param uuid
	 * @return
	 */
	public CdDocShareVo getById(String uuid){
		if(StringUtils.isEmpty(uuid)){
			return null;
		}
		CdDocShareVo cdDocShareVo = cdDocShareMapper.getById(uuid);
		return cdDocShareVo;
	}
	
	/**
	 * 新增 
	 * @param CdDocShareVo
	 * @return
	 */
	@Transactional
	public CdDocShareVo insert(CdDocShareVo cdDocShareVo) {
		cdDocShareVo.setUuid(super.getUUID());
		cdDocShareMapper.insert(cdDocShareVo);
		//日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_ADD, cdDocShareVo.getUuid(),"添加给分享的文件或者文件夹");
		return cdDocShareVo;
	}
	/**
	 * 通过empNo查询分享的数据
	 * @return
	 */
	public List<CdDocShareBo> selectShareFolder(){
		List<CdDocShareBo> cdDocShareResultBos = Lists.newArrayList();
		Map<String, Object> map = new HashMap<String,Object>();
		//是否共享
		map.put("shared", CommonConstant.COMMON_YES);
		//创建这者
		SessionUserHolder sessionUser = SessionUserUtil.getCurrentUser();
		map.put("createEmpNo", sessionUser.getUserNo());
		//是否删除
		map.put("isDel", CommonConstant.COMMON_NO);
		cdDocShareResultBos = cdDocShareMapper.selectShareFolder(map);
		//联合查询得到我分享的文件 和 我 文件夹信息
		return cdDocShareResultBos;
	}

/******************************************私有分享给个人*******************************/
	
	/**
	 * 私密分享 给个人 插入语句
	 * @param uuid 文档的id
	 * @param person 人员
	 */
	/*@Transactional
	public void sharePerson(String uuid,String person){
		//修改folder表中是否共享
		cdDocFileService.updateShared(uuid);
		
		//向分享表查询数据
		CdDocShareVo cdDocShareVo = insertBaseCdDocShare(uuid);

		CdDocShareAuthVo cdDocShareAuthVo= null;
		
		String[] splitPerson = person.split(",");
		
		AuapTEmpVo empVo = null;
		for (int i = 0; i < splitPerson.length; i++) {
			empVo = new AuapTEmpVo();
			cdDocShareAuthVo = new CdDocShareAuthVo();
			empVo = empService.getById(splitPerson[i]);
			//文档ID
			cdDocShareAuthVo.setShareId(cdDocShareVo.getUuid());
			//由于是公开分享暂时不考虑 分享目标类型  和 暂时不考虑targetId
			//分享目标类型（个人、角色、项目） 个人
			cdDocShareAuthVo.setTargetType(ShareConstant.SHARE_GOAL_TYPE_PERSON);
			//由于是公开分享暂时不考虑targetId 就是empNo 
			cdDocShareAuthVo.setTargetId(empVo.getEmpNo());
			cdDocShareAuthService.insert(cdDocShareAuthVo);		
		}
		
	}*/
	/**
	 * 分享文件时修改cdDocShareVo表中的数据
	 * @return
	 */
	/*public CdDocShareVo insertBaseCdDocShare(String uuid){
			
				//通过uuid查询数据文件或 文件夹得信息
				CdDocFolderVo cdDocFolderVo = cdDocFileService.getById(uuid);
				CdDocShareVo cdDocShareVo = new CdDocShareVo();
				//分享方式公开
				cdDocShareVo.setShareType(ShareConstant.DOCUMENT_SHARE_TYPE_PRIVATE);
				//文档类型
				cdDocShareVo.setFolderType(cdDocFolderVo.getFolderType());
				//文档id
				cdDocShareVo.setFolderId(cdDocFolderVo.getUuid());
				//浏览次数
				cdDocShareVo.setViewCnt(0L);
				//下载次数
				cdDocShareVo.setDownCnt(0L);
				//保存次数
				cdDocShareVo.setSaveCnt(0L);
				//分享人
				cdDocShareVo.setCreateEmpNo(cdDocFolderVo.getCreateEmpNo());
			
				//插入数据
				CdDocShareVo cdDocShareVo2 = insert(cdDocShareVo); 
				return cdDocShareVo2;
	}
	*/
	
	/************************************分享给角色*************************************/
	/**
	 * 私密分享 给角色 
	 * @param uuid
	 * @param role
	 */
	@Transactional
	/*public void privateShareRole(String uuid,String role){
		//通过角色查询查询人员的去掉重复是   auap_r_emp_org_role
		Set<String> set = new HashSet<String>();
		set = selectEmpIdRoleId(role);
		//folder表 把相关表修改成共享
		cdDocFileService.updateShared(uuid);
		//向分享表查询数据
		CdDocShareVo cdDocShareVo = insertBaseCdDocShare(uuid);
		
		AuapTEmpVo auapTEmpVo = null;
		CdDocShareAuthVo cdDocShareAuthVo= null;
		List<AuapTEmpVo> auapTEmpVos = selectEmpNoUuid(set);
		//在向分享的人员表插入数据
		for (AuapTEmpVo auapTEmpVo2 : auapTEmpVos) {
			//去掉当期用户
			if(!auapTEmpVo2.getEmpNo().equals(getEmpNo())){
				auapTEmpVo = new AuapTEmpVo();
				cdDocShareAuthVo= new CdDocShareAuthVo();
				//文档ID
				cdDocShareAuthVo.setShareId(cdDocShareVo.getUuid());
				//由于是公开分享暂时不考虑 分享目标类型  和 暂时不考虑targetId
				//分享目标类型（个人、角色、项目） 个人
				cdDocShareAuthVo.setTargetType(ShareConstant.SHARE_GOAL_TYPE_ROLE);
				//由于是公开分享暂时不考虑targetId 就是empNo 
				cdDocShareAuthVo.setTargetId(auapTEmpVo2.getEmpNo());
				cdDocShareAuthService.insert(cdDocShareAuthVo);		
			}
			
			
		}
	}*/
	/**
	 * 通过角色id查询出员工的id
	 * @param role
	 * @return
	 */
	public Set<String> selectEmpIdRoleId(String role){
		Set<String> set = new HashSet<String>();
		String[] splitString = role.split(",");
		List<AuapREmpOrgRoleVo> list =Lists.newArrayList();
		Map<String, Object> map = null;
		for (String roleId : splitString) {
			map = new HashMap<String,Object>();
			map.put("roleId", roleId);
			list = empOrgRoleMapper.queryForList(map);
			for (AuapREmpOrgRoleVo auapREmpOrgRoleVo : list) {
				set.add(auapREmpOrgRoleVo.getEmpId());
			}
		}	
		return set;
	}
	/**
	 * 通过员工uuid查询
	 * @param set
	 * @return
	 */
	public List<AuapTEmpVo> selectEmpNoUuid(Set<String> set){
		List<AuapTEmpVo> list = Lists.newArrayList();
		AuapTEmpVo auapTEmpVo = null;
		for (int i = 0; i < set.size(); i++) {	
			auapTEmpVo = new AuapTEmpVo();
			Iterator<String> iterator = set.iterator();
				while(iterator.hasNext()){
					auapTEmpVo = empMapper.getById(iterator.next());
					list.add(auapTEmpVo);
				}
		}
		return list;
	}
	
	/*********************************根据项目成员分享***********************************/
	/**
	 * 私密分享给项目下面的相关成员
	 * @param uuid
	 * @param project
	 *//*
	@Transactional
	public void privateProject(String uuid,String project){
		//通过项目的id查询 temp下面的相关成员
		Set<String> set = new HashSet<String>();
		set = selectTeamAll(project);
		
		//folder表 把相关表修改成共享
		cdDocFileService.updateShared(uuid);
		//向分享表查询数据
	
		CdDocShareVo cdDocShareVo = insertBaseCdDocShare(uuid);
		CdDocShareAuthVo cdDocShareAuthVo = null;
		Iterator<String> iterator = set.iterator();
		while(iterator.hasNext()){
			//去掉当期用户
			if(!iterator.next().equals(getEmpNo())){
				cdDocShareAuthVo = new CdDocShareAuthVo();
				//文档ID
				cdDocShareAuthVo.setShareId(cdDocShareVo.getUuid());
				//由于是公开分享暂时不考虑 分享目标类型  和 暂时不考虑targetId
				//分享目标类型（个人、角色、项目） 个人
				cdDocShareAuthVo.setTargetType(ShareConstant.SHARE_GOAL_TYPE_PROJECT);
				//由于是公开分享暂时不考虑targetId 就是empNo 
				cdDocShareAuthVo.setTargetId(iterator.next());
				
				cdDocShareAuthService.insert(cdDocShareAuthVo);	
			}
			
				
		}
		
		
	}*/
	/**
	 * 通过项目的prjId查询满足条件的EmpNo
	 */
	public Set<String> selectTeamAll(String project){
		
		Set<String> set = new HashSet<String>();
		String[] splitProject = project.split(",");
		List<TeamVo> list = Lists.newArrayList();
		for (int i = 0; i < splitProject.length; i++) {
			list = teamService.findByPrjId(splitProject[i]);
			for (TeamVo teamVo : list) {
				set.add(teamVo.getEmpNo());
			}
		}
		return set;
	}
	/**
	 *查询我分享的文档
	 */
	public List<CdDocFolderVo> query(String targetId){
		List<CdDocFolderVo> list = Lists.newArrayList();
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("targetId", targetId);
		return list =  docFileMapper.getShare(map);
	}
	
	/**
	 * 取消分享
	 * @param folderId
	 */
	@Transactional
	public void deleteShareFile(String[] uuid){
		Map<String, Object> map;
		for (int i = 0; i < uuid.length; i++) {
			map = new HashMap<String,Object>();
			map.put("shared", CommonConstant.COMMON_NO);
			map.put("uuid",uuid[i]);
			docFileMapper.updateShared(map); 

			//日志
			super.invokeLogInsert( "400000000012", LogConstant.LOG_DELETE, uuid[i],"取消分享");
		}
		
	}
	
	
	/**
	 * 查询相关分享的数据
	 * @return
	 */
	public CdDocShareBo queryForListShare(String uuid,String empNo){
		
		CdDocShareBo cdDocShareBo = new CdDocShareBo();
		
		CdDocShareVo cdDocShareVo = cdDocShareMapper.selectFolderId(uuid); 
		//把数据复制到cdDocShareBo中	
		BeanUtils.copyProperties(cdDocShareVo,cdDocShareBo);
		
		List<CdDocShareAuthVo> cdDocShareAuthVos = cdDocShareAuthMapper.getShareId(uuid);
		
		cdDocShareBo.setShareAuthList(cdDocShareAuthVos);
		return cdDocShareBo;	
	}
	
	/**
	 * 查询文件是否共享 
	 * @return
	 */
	public CdDocShareBo addShare(String uuid,String empNo){
		CdDocShareBo cdDocShareBo = new CdDocShareBo();
		//首先查出folder是否共享
		
		CdDocFolderVo cdDocFolderVo =cdDocFileService.getById(uuid);
		
		if(StringUtils.isEmpty(cdDocFolderVo.getShared())||CommonConstant.COMMON_NO.equals(cdDocFolderVo.getShared())){
			//判断原来是否共享过
			return cdDocShareBo;
		}else{
			//查询数据
		
			cdDocShareBo = queryForListShare(uuid, empNo);
			return cdDocShareBo;
		}
		
	}
	
	/****************************************修改分享***********************************************/
	/**
	 * 修改分享 就是删除
	 * @param uuid
	 */
	public void deleteshareIdJoin(String folderId){
		//通过share表中的uuid删除数据分享share_auth表中的数据
		cdDocShareAuthMapper.deleteshareIdJoin(folderId);
		//日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_DELETE, LogConstant.LOG_DELETE,"修改分享");
	}
	/**
	 * 通过folderId查询数据
	 * @param folderId
	 * @return
	 */
	public List<CdDocShareVo> cdDocShareVo(String folderId){
		List<CdDocShareVo> cdDocShareVos = Lists.newArrayList();
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("folderId", folderId);
		cdDocShareVos = cdDocShareMapper.queryForList(param);
		return cdDocShareVos;
	}
	

	
	/**********************************私密 保存分享******************************************/
	/**
	 * 保存分享
	 * @param person 人员id
	 * @param role 角色id
	 * @param project 项目id
	 * @param shareType 分享类型
	 * @param uuid 文件 或者 文件夹 id
	 * @param empNo 当前用户
	 */
	@Transactional
	public void addPrivatePersonRolePrject(String person,String role,String project,String shareType, String uuid,String empNo){
		
		
		//把folder表数据修改成共享
		 cdDocFileService.updateShared(uuid);
		 //查询share表有没有分享文件
		 List<CdDocShareVo> cdDocShareVos = cdDocShareVo(uuid);
		 CdDocShareVo cdDocShareVo2 =new CdDocShareVo();
		 if(Collections3.isEmpty(cdDocShareVos)){
			   CdDocFolderVo cdDocFolderVo = cdDocFileService.getById(uuid);
				CdDocShareVo cdDocShareVo = new CdDocShareVo();
				//分享方式
				cdDocShareVo.setShareType(shareType);
				//文档类型
				cdDocShareVo.setFolderType(cdDocFolderVo.getFolderType());
				//文档id
				cdDocShareVo.setFolderId(cdDocFolderVo.getUuid());
				//浏览次数
				cdDocShareVo.setViewCnt(0L);
				//下载次数
				cdDocShareVo.setDownCnt(0L);
				//保存次数
				cdDocShareVo.setSaveCnt(0L);
				//分享人
				cdDocShareVo.setCreateEmpNo(cdDocFolderVo.getCreateEmpNo());
				//插入数据
				
				 cdDocShareVo2 = insert(cdDocShareVo); 
				 cdDocShareAuthService.addPerson(person,cdDocShareVo2.getUuid());
				 cdDocShareAuthService.addProject(project,cdDocShareVo2.getUuid());
				 cdDocShareAuthService.addRole(role,cdDocShareVo2.getUuid());	 
		 }else{
			 //删除所有数据
			 //通过folder查询出数据
			 //把共享修改
			 Map<String, Object> map = new HashMap<String,Object>();
			 map.put("folderId", uuid);
			 map.put("shareType",shareType);
			 cdDocShareMapper.updateShareType(map);
			 CdDocShareVo cdDocShareVo = cdDocShareMapper.selectFolderId(uuid);
			 cdDocShareAuthService.deleteShareId(cdDocShareVo.getUuid());
			 cdDocShareAuthService.addPerson(person,cdDocShareVo.getUuid());
			 cdDocShareAuthService.addProject(project,cdDocShareVo.getUuid());
			 cdDocShareAuthService.addRole(role,cdDocShareVo.getUuid());
		 }
		
	}
	
	/*********************************公开分享**********************************************/	
	/**
	 * 公开分享 任何人都可以看到 就不需要targetId 直接不存值  插入失败事务 回滚问题 
	 * @param uuid
	 * @return
	 */
	@Transactional
	public void saveShare(String uuid){
		//把folder表数据修改成共享
		 cdDocFileService.updateShared(uuid);
		 //查询share表有没有分享文件
		 List<CdDocShareVo> cdDocShareVos = cdDocShareVo(uuid);
		 CdDocShareVo cdDocShareVo2 =new CdDocShareVo();
		 if(Collections3.isEmpty(cdDocShareVos)){
			   CdDocFolderVo cdDocFolderVo = cdDocFileService.getById(uuid);
				CdDocShareVo cdDocShareVo = new CdDocShareVo();
				//分享方式
				cdDocShareVo.setShareType(ShareConstant.DOCUMENT_SHARE_TYPE_PUBLIC);
				//文档类型
				cdDocShareVo.setFolderType(cdDocFolderVo.getFolderType());
				//文档id
				cdDocShareVo.setFolderId(cdDocFolderVo.getUuid());
				//浏览次数
				cdDocShareVo.setViewCnt(0L);
				//下载次数
				cdDocShareVo.setDownCnt(0L);
				//保存次数
				cdDocShareVo.setSaveCnt(0L);
				//分享人
				cdDocShareVo.setCreateEmpNo(cdDocFolderVo.getCreateEmpNo());
				//插入数据
				 cdDocShareVo2 = insert(cdDocShareVo); 
				 CdDocShareAuthVo cdDocShareAuthVo = new CdDocShareAuthVo();
				//文档ID
				cdDocShareAuthVo.setShareId(cdDocShareVo2.getUuid());
				 cdDocShareAuthService.insert(cdDocShareAuthVo);	
		 }else{
			 //删除所有数据
			 //通过folder查询出数据
			 //修改为公开分享
			 Map<String, Object> map = new HashMap<String,Object>();
			 map.put("folderId", uuid);
			 map.put("shareType",ShareConstant.DOCUMENT_SHARE_TYPE_PUBLIC);
			 cdDocShareMapper.updateShareType(map);
			 //删除
			 CdDocShareVo cdDocShareVo = cdDocShareMapper.selectFolderId(uuid);
			 cdDocShareAuthService.deleteShareId(cdDocShareVo.getUuid());
				CdDocShareAuthVo cdDocShareAuthVo = new CdDocShareAuthVo();
				//文档ID
				cdDocShareAuthVo.setShareId(cdDocShareVo.getUuid());
				//由于是公开分享暂时不考虑 分享目标类型  和 暂时不考虑targetId
				//分享目标类型（个人、角色、项目）公开分享设置为空
				//cdDocShareAuthVo.setTargetType("");
				//由于是公开分享暂时不考虑targetId 就是empNo 设置为空
				//cdDocShareAuthVo.setTargetId("");
				cdDocShareAuthService.insert(cdDocShareAuthVo);	
		 }
	}
}
